﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Cms.Application;
using Cms.Application.Admin.Presenters;
using Cms.Application.Admin.Views;
using Cms.Domain;
using Cms.Web.Framework.Controls;
using Cms.Web.UI.Admin.HelperClasses;
using iLib.Web.UI;
using iLib.Web.UI.WebControls;

namespace Cms.Web.UI.Admin.TinyMCEIntegration
{
    public partial class MediaPopup : AdminPopupBasePage, IMediaView
    {
        private MediaPresenter _presenter;

        #region IMediaView Members

        public string ContextTranslationFile
        {
            get { return "Admin/Translations/Media.xml"; }
        }

        public void RemoveFileFromOutputCache(string virtualPath)
        {
            HttpContext.Current.Cache.Insert(virtualPath, "remove", null, DateTime.Now.AddDays(-1), TimeSpan.Zero);
        }

        public void SetMediaFolders(string rootMediaFolder, IList<MediaFolder> mediaFolders)
        {
            hidSelectedFolderPath.Value = rootMediaFolder;

            // This will be replaced if a folder is selected (in the RenderFolders method)
            string html = "<span id=\"rootMediaFolder\"";
            if (SelectedMediaFolderId == -1)
            {
                html += " class=\"selected\"";
            }
            html += "><img src=\"Admin/Img/icons/drive.png\" /><span>" + rootMediaFolder + "</span></span>";
            RenderFolders(ref html, mediaFolders);
            /*
            <ul>
                <li>
                    <a href="#"><img src="Admin/Img/treenodeClosed.gif" /></a><span id="A"><img src="Admin/Img/icons/folder.png" /><span>Aaaaaa</span></span>
                    <ul>
                        <li>
                            <a href="#"><img src="Admin/Img/treenodeClosed.gif" /></a><span id="F"><img src="Admin/Img/icons/folder.png" /><span>Ffffffffff</span></span>
                            <ul>
                                <li>
                                    <img src="Admin/Img/tp.gif" width="6" height="9" /><span id="G"><img src="Admin/Img/icons/folder.png" /><span>Ggggggggg</span></span>
                                </li>
                                <li>
                                    <img src="Admin/Img/tp.gif" width="6" height="9" /><span id="H"><img src="Admin/Img/icons/folder.png" /><span>Hhhhhhhhhh</span></span>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </li>
                <li>
                    <img src="Admin/Img/tp.gif" width="6" height="9" /><span id="B"><img src="Admin/Img/icons/folder.png" /><span>Bbbbbbbb</span></span>
                </li>
            </ul>
            */
            litFolders.Text = html;
            upnlActions.Update();
        }

        public void SetMediaFiles(IList<MediaFile> files)
        {
            rpFiles.DataSource = files;
            rpFiles.DataBind();
            pnlNoFiles.Visible = rpFiles.Items.Count == 0;
        }

        public int SelectedMediaFolderId
        {
            get
            {
                if (hidSelectedFolderID.Value == "rootMediaFolder")
                {
                    return -1;
                }
                return int.Parse(hidSelectedFolderID.Value.Substring(1));
            }
            set
            {
                if (value == -1)
                {
                    hidSelectedFolderID.Value = "rootMediaFolder";
                }
                else
                {
                    hidSelectedFolderID.Value = "F" + value;
                }
            }
        }
        
        public string SelectedIDs
        {
            get
            {
                if (ViewState["SelectedIDs"] == null)
                {
                    ViewState["SelectedIDs"] = string.Empty;
                }
                return (string)ViewState["SelectedIDs"];
            }
            set
            {
                ViewState["SelectedIDs"] = value;
            }
        }
        
        public string SelectedGroupAction
        {
            get
            {
                if (ViewState["SelectedGroupAction"] == null)
                {
                    ViewState["SelectedGroupAction"] = string.Empty;
                }
                return (string)ViewState["SelectedGroupAction"];
            }
            set
            {
                ViewState["SelectedGroupAction"] = value;
            }
        }
        
        public string Localization
        {
            get
            {
                HttpCookie cookie = Request.Cookies["FrediumAdminLocalization"];
                if (cookie != null)
                {
                    return cookie.Value;
                }
                return "en-US";
            }
        }

        #endregion

        protected string GetText(ITranslatable view, string key)
        {
            return Translator.GetText(view.ContextTranslationFile, key, view.Localization);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            baseTag.Attributes.Add("href", Url.FullPath);
            _presenter = new MediaPresenter(this);
            Title = GetText(this, "Heading");
            Page.Header.Controls.Add(new iLibRegistrator());
            if (!Page.IsPostBack)
            {
                _presenter.Initialize();
                form1.Action = Url.FoldersAndPage + Url.Querystring;
            }
            lbDeleteFolder.OnClientClick = "return cms.Dialogs.ConfirmLinkButton(this, " +
                                               "function (status) { " +
                                                   "if (status == 'ok') " +
                                                        "cms.Lists.ShowPaneOverlay('folderPaneOverlay');" +
                                                   "else " +
                                                        "cms.Lists.HidePaneOverlays(); " +
                                               "}, " +
                                               "'" + GetText(this, "DeleteHeader") + "', " +
                                               "'" + GetText(this, "DeleteSingleFolderMessage") + "', " +
                                               "'" + GetText(this, "DeleteOK") + "', " +
                                               "'" + GetText(this, "DeleteCancel") + "', " +
                                               "true, " +
                                               "cms.Lists.CurrentName);";
            lbDeleteSingleFile.OnClientClick = "return cms.Dialogs.ConfirmLinkButton(this, " +
                                                   "function (status) { " +
                                                       "if (status == 'ok') " +
                                                            "cms.Lists.ShowPaneOverlay('filePaneOverlay');" +
                                                       "else " +
                                                            "cms.Lists.HidePaneOverlays(); " +
                                                   "}, " +
                                                   "'" + GetText(this, "DeleteHeader") + "', " +
                                                   "'" + GetText(this, "DeleteSingleFileMessage") + "', " +
                                                   "'" + GetText(this, "DeleteOK") + "', " +
                                                   "'" + GetText(this, "DeleteCancel") + "', " +
                                                   "true, " +
                                                   "cms.Lists.CurrentName);";
            lbDeleteMultipleFiles.OnClientClick = "return cms.Dialogs.ConfirmLinkButton(this, " +
                                                      "function (status) { " +
                                                          "if (status == 'ok') " +
                                                                "cms.Lists.ShowPaneOverlay('filePaneOverlay');" +
                                                          "else " +
                                                                "cms.Lists.HidePaneOverlays(); " +
                                                      "}, " +
                                                      "'" + GetText(this, "DeleteHeader") + "', " +
                                                      "'" + GetText(this, "DeleteMultipleFilesMessage") + "', " +
                                                      "'" + GetText(this, "DeleteOK") + "', " +
                                                      "'" + GetText(this, "DeleteCancel") + "', " +
                                                      "true);";
            string confirmDragScript = "function confirmDrag(draggedElement, dropzoneElement) { " +
                                            "var message = '" + GetText(this, "DragWarningMessage") + "';" +
                                            "message = message.replace(/\\[\\[draggedElement\\]\\]/gi, cms.Utils.GetInnerText(draggedElement));" +
                                            "message = message.replace(/\\[\\[dropzoneElement\\]\\]/gi, cms.Utils.GetInnerText(dropzoneElement));" +
                                            "cms.Dialogs.Confirm(function (status) { " +
                                                "if (status == 'ok') { " +
                                                    "cms.Lists.ShowPaneOverlay('filePaneOverlay');" +
                                                    "cms.Lists.ShowPaneOverlay('folderPaneOverlay');" +
                                                    "__doPostBack('lbDragEnd', '');" +
                                                "} " +
                                                "else " +
                                                    "cms.Lists.HidePaneOverlays(); " +
                                            "}, " +
                                            "'" + GetText(this, "DragWarningHeader") + "', " +
                                            "message, " +
                                            "'" + GetText(this, "DragWarningOK") + "', " +
                                            "'" + GetText(this, "DragWarningCancel") + "', " +
                                            "true);" +
                                        "}";
            this.ClientScript.RegisterClientScriptBlock(this.GetType(), "confirmDragScript", confirmDragScript, true);
        }
        
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            hlUpload.NavigateUrl = "Admin/TinyMCEIntegration/UploadFilesPopup.aspx";
            hlNewFolder.NavigateUrl = "Admin/TinyMCEIntegration/EditMediaFolderPopup.aspx";
            UpdateButtons();
            upnlButtons.Update();
            UpdateFolderPane();
            UpdateFilePane();
            Page.Validate();
            pnlError.Visible = !Page.IsValid;
            Page.Header.Controls.AddAt(
                0,
                new LiteralControl("<script type=\"text/javascript\" src=\"" +
                                ConfigurationManager.AppSettings["jQueryPath"] +
                                "\"></script>"));
        }
       
        protected void lbDragEnd_Click(object sender, EventArgs e)
        {
            if (hidDropzoneID.Value == string.Empty)
            {
                return;
            }
            _presenter.Move(hidDraggedID.Value, hidDropzoneID.Value);
        }
        
        protected void btnSelectFolder_Click(object sender, EventArgs e)
        {
            _presenter.SetMediaFolders();
            _presenter.SetMediaFiles();
            hidSelectedFolderPath.Value = _presenter.GetSelectedFolderPath();
            chkAll.Checked = false;
            upnlActions.Update();
        }

        protected void btnToggleFolder_Click(object sender, EventArgs e)
        {
            _presenter.ToggleMediaFolder(int.Parse(hidToggleFolderId.Value));
            UpdateFolderPane();
        }

        protected void lbDeleteFolder_Click(object sender, EventArgs e)
        {
            _presenter.DeleteMediaFolder(int.Parse(hidDeleteFolderID.Value.Substring(1)));
        }
        
        protected void lbDeleteSingleFile_Click(object sender, EventArgs e)
        {
            _presenter.DeleteMediaFile(int.Parse(hidSelectedFileID.Value.Substring(1)));
            _presenter.SetMediaFiles();
        }

        protected void lbPreviewFile_Click(object sender, EventArgs e)
        {
            MediaFile file = _presenter.GetMediaFile(int.Parse(hidSelectedFileID.Value.Substring(1)));
            bool showPreviewDialog = false;
            switch (file.Extension.ToLower())
            {
                case "gif":
                case "jpg":
                case "png":
                case "pdf":
                case "htm":
                case "html":
                case "xml":
                case "swf":
                case "php":
                case "asp":
                case "aspx":
                    ifrPreviewFile.Attributes.Add("src", Url.VirtualPath + file.GetVirtualPath() + "?v=" + file.Version);
                    showPreviewDialog = true;
                    break;
                case "xls":
                case "xlsx":
                case "doc":
                case "docx":
                case "ppt":
                case "pptx":
                case "mdb":
                case "zip":
                case "mp3":
                    ifrPreviewFile.Attributes.Add("src", Url.VirtualPath + file.GetVirtualPath() + "?v=" + file.Version);
                    break;
                case "txt":
                case "js":
                    break;
            }
            if (showPreviewDialog)
            {
                litPreviewFileName.Text = file.Name;
                string script = "cms.Dialogs.CustomAlert(null, 'Info', 'OK', 'previewDiv');";
                ClientScriptProxy.Current.RegisterStartupScript(pnlFilePreviewAction, GetType(), "previewFile", script, true);
            }
            upnlPreviewFile.Update();
        }
        
        protected void lbSync_Click(object sender, EventArgs e)
        {
            _presenter.Sync();
        }

        protected void lbZip_Click(object sender, EventArgs e)
        {
            PrepareGroupAction();
            string script = "cms.Dialogs.Confirm(zipCallback, '" + GetText(this, "ZipHeader") + "', null, '" +
                            GetText(this, "ZipOK") + "', '" + GetText(this, "ZipCancel") +
                            "', true, null, 'zip'); captureEnterForZipFilename();";
            ClientScriptProxy.Current.RegisterStartupScript(pnlButtonActions, GetType(), "zip", script, true);
            txtZip.Focus();
            upnlZip.Update();
        }

        protected void btnStartZipping_Click(object sender, EventArgs e)
        {
            _presenter.Zip(txtZip.Text);
            if (!_presenter.IsValid)
            {
                return;
            }
            chkAll.Checked = false;
            txtZip.Text = string.Empty;
            upnlZip.Update();
        }

        protected void lbUnzip_Click(object sender, EventArgs e)
        {
            _presenter.Unzip(int.Parse(hidSelectedFileID.Value.Substring(1)));
        }
        
        protected void lbCut_Click(object sender, EventArgs e)
        {
            PrepareGroupAction();
            SelectedGroupAction = "cut";
        }

        protected void lbCopy_Click(object sender, EventArgs e)
        {
            PrepareGroupAction();
            SelectedGroupAction = "copy";
        }
        
        protected void lbPaste_Click(object sender, EventArgs e)
        {
            _presenter.Paste();
        }
        
        protected void lbDeleteMultipleFiles_Click(object sender, EventArgs e)
        {
            foreach (RepeaterItem ri in rpFiles.Items)
            {
                var chkMedia = (iCheckBox)ri.FindControl("chkMedia");
                if (chkMedia.Checked)
                {
                    _presenter.DeleteMediaFile(int.Parse(chkMedia.Value));
                }
            }
            _presenter.SetMediaFiles();
        }

        protected void rpFiles_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            MediaHelper.rpFiles_ItemDataBound(sender, e, GetText(this, "Pixels"), GetText(this, "AllowAccessForEveryone"));
        }

        private void UpdateButtons()
        {
            int checkedCount = 0;
            foreach (RepeaterItem ri in rpFiles.Items)
            {
                if ((ri.FindControl("chkMedia") as iCheckBox).Checked)
                {
                    checkedCount++;
                }
            }
            chkAll.Checked = checkedCount > 0 && checkedCount == rpFiles.Items.Count;
            lbDeleteMultipleFiles.Visible = checkedCount > 0;
            lbCut.Visible = checkedCount > 0;
            lbCopy.Visible = checkedCount > 0;
            lbZip.Visible = checkedCount > 0;
            lbPaste.Visible = SelectedIDs != string.Empty && SelectedGroupAction != string.Empty;
            lblButtonDivider.Visible = checkedCount > 0 || (SelectedIDs != string.Empty && SelectedGroupAction != string.Empty);
        }

        private void PrepareGroupAction()
        {
            iCheckBox chkMedia;
            foreach (RepeaterItem ri in rpFiles.Items)
            {
                chkMedia = ri.FindControl("chkMedia") as iCheckBox;
                if (chkMedia.Checked)
                {
                    if (SelectedIDs != string.Empty)
                    {
                        SelectedIDs += ",";
                    }
                    SelectedIDs += "M" + chkMedia.Value;
                }
            }
        }

        private void UpdateFolderPane()
        {
            upnlFolders.Update();
            ClientScriptProxy.Current.RegisterStartupScript(pnlFolderActions, GetType(), "initFolderList", "initFolderList();", true);
        }

        private void UpdateFilePane()
        {
            upnlFiles.Update();
            ClientScriptProxy.Current.RegisterStartupScript(pnlFileActions, GetType(), "initFileList", "initFileList();", true);
        }
                
        private void RenderFolders(ref string html, IList<MediaFolder> mediaFolders)
        {
            if (mediaFolders.Count == 0)
            {
                return;
            }
            html += "<ul>";
            foreach (MediaFolder folder in mediaFolders)
            {
                html += "<li>";
                if (folder.SubFolders.Count == 0)
                {
                    html += "<a href=\"javascript:void();\" class=\"empty\"></a>";
                }
                else
                {
                    html += "<a href=\"javascript:void();\" id=\"T" + folder.ID + "\" class=\"";
                    html += _presenter.IsMediaFolderClosed(folder.ID) ? "closed" : "open";
                    html += "\"></a>";
                }
                html += "<span id=\"F" + folder.ID + "\"";
                if (SelectedMediaFolderId == folder.ID)
                {
                    html += " class=\"selected\"";
                    hidSelectedFolderPath.Value = folder.GetVirtualPath();
                }
                html += "><img src=\"Admin/Img/icons/folder.png\" /><span>" + folder.Name + "</span></span>";
                html += "</li>";
                if (!_presenter.IsMediaFolderClosed(folder.ID))
                {
                    RenderFolders(ref html, folder.SubFolders);
                }
            }
            html += "</ul>";
        }
    }
}